package server;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Main class that accepts connections from users
 * 
 * @author Michele Massaro 1057513
 *
 */
public class Listener {

	static {
	      System.setProperty("java.awt.headless", "true");
	    }
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		
		
		ServerSocket server = null;
		
		// work folder passed as arg
		if(args.length != 1) {
			System.out.println("Application usage: java -jar MySightServer.jar <path to index.php>");
			System.exit(0);
		}
		
		String imageFolder = "";
		String thumbFolder = "";
		
		try {
			server = new ServerSocket(8090);

			// create work folders
			File file = new File(args[0]);
			String path = "";

			if (file.exists()) {
				if (args[0].endsWith("/")) {
					path = args[0];
				} else {
					path = args[0] + "/";
				}
			} else {
				System.out.println("Path not found");
				System.exit(0);
			}

			imageFolder = path + "pic/";
			file = new File(imageFolder);
			if (file.exists() || file.mkdir()) {
				System.out.println("Picture folder created");
			} else {
				System.out
						.println("Error while creating folder, check your privileges on "
								+ path);
				System.exit(0);
			}

			thumbFolder = path + "thumb/";
			file = new File(thumbFolder);
			if (file.exists() || file.mkdir()) {
				System.out.println("Workspace prepared");
			} else {
				System.out
						.println("Error while creating folder, check your privileges on "
								+ path);
				System.exit(0);
			}

		} catch (IOException e) {
			System.out.println("An error occurred opening the socket");
			System.exit(-1);
		}
		
		System.out.println("Server started");
		
		UserList list = new UserList();
		
		while(true) {
			try {
				Socket client = server.accept();
				ConnectionThread ct = new ConnectionThread(client, list, imageFolder, thumbFolder);
				Thread user = new Thread(ct);
				user.start();
			} catch (IOException e) {
				System.out.println("New connection with client failed");
			}
		}

	}

}
